package com.papper.common.service.sys;

import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import com.papper.common.bean.sys.SysLimit;
import com.papper.common.bean.sys.SysModel;
import com.papper.common.bean.sys.SysResource;
import com.papper.common.bean.sys.SysUser;
import com.papper.common.enums.DataStatusEnum;
import com.papper.common.mapper.sys.SysModelMapper;
import com.papper.common.service.ServiceImpl;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

@Service("sysModelService")
public class SysModelService extends ServiceImpl<SysModelMapper, SysModel> {
	@Resource
	SysLimitService    sysLimitService;
	@Resource
	SysResourceService sysResourceService;

	/**
	 * function
	 */
	public List<SysModel> findBySystemId(Long systemId) {
		if (systemId == null) {
			return null;
		}
		Example example = new Example(SysModel.class);
		example.createCriteria().andEqualTo("systemId", systemId);
		if (StringUtil.isEmpty(example.getOrderByClause())) {
			example.setOrderByClause("model_sort asc");
		}
		return find(example);
	}

	public List<SysModel> findByLimit(Long systemId, SysUser sysUser) {
		// 超级用户
		if (sysUser.getId() == 0) {
			return findBySystemId(systemId);
		}
		// 获取权限信息
		List<SysLimit> userLimits = sysLimitService.getUserLimits(sysUser);
		Set<String>    ids        = Sets.newHashSet();
		if (userLimits != null && !userLimits.isEmpty()) {
			for (SysLimit sysLimit : userLimits) {
				ids.add(sysLimit.getResId().toString());
			}
		}
		// 获取资源列表
		List<SysResource> sysResources = sysResourceService.findByIds(ids);
		Set<Integer>      modelIds     = Sets.newHashSet();
		if (sysResources != null && !userLimits.isEmpty()) {
			for (SysResource sysResource : sysResources) {
				if (sysResource.getDataStatus().intValue() == DataStatusEnum.CLOSE.getCode().intValue()) {
					continue;
				}
				modelIds.add(sysResource.getModelId());
			}
		}
		// 获取模块列表
		return findByIds(Joiner.on(",").skipNulls().join(modelIds));
	}

	/**
	 * function
	 */
	public void deleteBySystemId(Long systemId) {
		Example example = new Example(SysModel.class);
		example.createCriteria().andEqualTo("systemId", systemId);
		delete(example);
	}
}